import React, { PureComponent } from 'react';
import {
  Row,
  Col,
  Input,
  Spin,
  Upload,
  Descriptions,
  Button,
  Icon,
  message,
  Card,
  Tabs,
  Dropdown,
  Menu,
} from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import FileBtn from '@/components/FileBtn';
import qs from 'qs';
import styles from './index.less';
import * as api from '@/services/ValueApprovelMgr';
import { getPageQuery, showConfirm } from '@/utils/utils';
import { createUploadUsingPOST } from '@/services/upload';
import PageEmpty from '@/components/PageEmpty';
import DifferenceOlive from './components/DifferenceOlive';
import DifferenceDetail from './components/DifferenceDetail';
import PriceAdjustmentBuilding from './components/PriceAdjustmentBuilding';
import IndicatorImpact from './components/IndicatorImpact';
import WarningBriefing from './components/WarningBriefing';
import ProjectBackgroundStrategy from './components/ProjectBackgroundStrategy';
import * as utils from './utils/treeUtils';

const { TextArea } = Input;
const { Dragger } = Upload;
const { TabPane } = Tabs;
function isEmpty(obj) {
  const reg = '^[ ]+$';
  const re = new RegExp(reg);
  if (typeof obj === 'undefined' || obj == null || obj === '' || re.test(obj)) {
    return true;
  }
  return false;
}
/**
 * 货值审批
 * 去掉项目阶段及其校验等相关逻辑校验
 * 剔除年初考核版均价、调整后-年初考核版均价列
 * 1 本次调价对整盘核心指标的影响
 1）集团版整列不可编辑
 2）投资版可编辑 ---显示编辑高亮
 3）调整后为整列必填

2 列顺序 投资>战规>集团>调整前>调整后

3 本次调整预警简报
增加非融IRR 非融静态投资回收期（月）
数据顺序 权益前货值（万元）> 创造利润率 > 非融IRR > 非融静态投资回收期（月）> 楼栋均价
 */

@connect(state => ({
  approve: state.Approve,
}))
class Approve extends PureComponent {
  state = {
    description: '',
    fileList: [],
    fileLoading: false,
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const { action, id, projectId } = location.query;
    const queryParams = getPageQuery();
    if (queryParams && queryParams.token) {
      if (dispatch) {
        dispatch({
          type: 'token/save',
          payload: queryParams.token,
        });
      }
    }
    if (!action) {
      const theHead = document.getElementsByTagName('head').item(0);
      // 创建脚本的dom对象实例
      const myScript = document.createElement('script');
      myScript.src = process.env.oaUrl;
      myScript.type = 'text/javascript';
      myScript.defer = true;
      theHead.appendChild(myScript);
    }

    const params = {
      projectId: projectId || '',
      businessKey: id || '',
    };
    if (dispatch) {
      dispatch({
        type: 'Approve/basicInfo',
        payload: { params },
        callback: data => {
          const fileList = [];
          // if (id) {
          _.forEach(data.files, file => {
            fileList.push({
              uid: file.fileId,
              name: file.fileName,
              filePath: file.filePath,
              previewUrl: file.previewUrl,
              status: 'done',
            });
          });

          this.setState({
            fileList,
            description: data.description,
          });
          // }

          dispatch({
            type: 'Approve/init',
            payload: { params },
            callback: list => {
              this.handleTabsKeyChange(list[0].type);
            },
          });
          dispatch({
            type: 'Approve/approvedInfo',
            payload: { params },
            callback: list => {
              Object.keys(list).forEach(key => {
                // 有动态版，大定价版 才显示对比信息
                if (list[key].indexOf('动态版') > -1 || list[key].indexOf('大定价') > -1) {
                  dispatch({
                    type: 'Approve/requestWarnInfo',
                    payload: { params },
                    projectType: data?.projectType,
                  });
                }
              });
            },
          });
        },
      });
    }
  }

  // tab 切换 获取key 值
  handleTabsKeyChange = key => {
    const { dispatch, location } = this.props;
    const { id, projectId } = location.query;
    const params = {
      projectId: projectId || '',
      businessKey: id || '',
    };
    dispatch({
      type: 'Approve/allgoodsValueDetail',
      payload: {
        params: {
          ...params,
          type: key,
        },
      },
      callback: () => {
        if (!location.query.action && window.cifioa) {
          window.cifioa.sendMessage({
            type: 'height',
            height: window.document.body.scrollHeight,
          });
        }
      },
    });
  };

  // 项目背景与价格策略
  handleChangeProjectBackgroundStrategy = (ev, rowProps, index) => {
    const {
      dispatch,
      approve: { backTacticsWarnInfoList },
    } = this.props;
    const text = ev.target.value;
    const cloneBackTacticsWarnInfoList = _.cloneDeep(backTacticsWarnInfoList);
    const newData = cloneBackTacticsWarnInfoList.map((item, idx) => {
      const itemX = item;
      if (idx === index) {
        itemX.content = text;
      }
      return itemX;
    });
    dispatch({
      type: 'Approve/save',
      payload: {
        backTacticsWarnInfoList: newData,
      },
    });
  };

  // 核心指标编辑
  handleChangeIndicators = (value, rowProps) => {
    const {
      approve: { coreWarnInfoList, bulletinWarnInfo },
      dispatch,
    } = this.props;
    const cloneCoreWarnInfoList = _.cloneDeep(coreWarnInfoList);
    const { column, rowIndex } = rowProps;
    const newData = cloneCoreWarnInfoList.list.map((item, idx) => {
      const itemX = item;
      if (idx === rowIndex) {
        itemX[column.key] = value;
      }
      return itemX;
    });
    const list = utils.getCoreWarnInfoList(newData);

    const bulletinWarn = utils.getBulletinWarnInfo(bulletinWarnInfo, list);

    dispatch({
      type: 'Approve/save',
      payload: {
        ...bulletinWarn,
        coreWarnInfoList: {
          ...coreWarnInfoList,
          list,
        },
      },
    });
  };

  /* 下载文件 */
  download = ({ uid }) => {
    const params = {
      fileId: uid,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    window.open(`${process.env.apiUrl}/api/v1/fileUpload/download?${exportQueryString}`);
  };

  // 请求提交审批
  requestSubmitApprove = (params, dispatch) => {
    this.setState({ loading: true });
    dispatch({
      type: 'Approve/approved',
      payload: { data: params },
      callback: data => {
        if (data && data.code * 1 === 1) {
          window.location.href = `${data.data.previewUrl}`;
        }
        this.setState({ loading: false });
      },
    });
  };

  // 导出
  onClickExportExcel = key => {
    let exportAddress = null;
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({
      businessKey: this.props.location.query.id,
      sessionToken,
    });
    if (key === 'EXPORT_1') {
      exportAddress = 'newAllgoodsValueReviewExport';
    }
    if (key === 'EXPORT_2') {
      exportAddress = 'newAllgoodsValueDetailExport';
    }
    if (key === 'EXPORT_3') {
      exportAddress = 'priceApprovalDifferencesBuildExport';
    }
    if (key === 'EXPORT_4') {
      exportAddress = 'priceApprovalCoreWarnExport';
    }

    if (exportAddress) {
      window.open(
        `${process.env.apiUrl}/api/v1/valueApprovel/${exportAddress}?${exportQueryString}`,
      );
    }
  };

  // 提交oa 审批单
  handApprove() {
    const { dispatch, approve, location } = this.props;
    const { description, fileList } = this.state;
    const { projectId, id } = location.query;
    const {
      backTacticsWarnInfoList,
      bulidWarnInfoList,
      bulletinWarnInfo,
      coreWarnInfoList,
      warnFlag,
      // contrastType,
    } = approve;
    // 判断调整后是否有值
    const isVals = _.filter(
      coreWarnInfoList.list,
      x => isEmpty(x.after) || isEmpty(x.before) || isEmpty(x.investment) || isEmpty(x.strategy),
    );
    if (!description) {
      message.warning('请填写审批要点说明');
      return;
    }
    if (!_.isEmpty(isVals)) {
      message.warning('整盘核心指标值不能为空');
      return;
    }
    // 处理参数
    const files = _.map(fileList, x => x.uid);
    const params = {
      projectId: projectId || '',
      businessKey: id || '',
      businessType: 'price_management',
      description,
      files,
      approveWarnInfoVO: {
        backTacticsWarnInfoList,
        bulidWarnInfoList: bulidWarnInfoList.list,
        bulletinWarnInfo,
        coreWarnInfoList: coreWarnInfoList.list,
        warnFlag,
      },
    };

    if (warnFlag) {
      showConfirm(
        () => this.requestSubmitApprove(params, dispatch),
        '触发货值预警提示',
        '已触发货值预警，确认是否继续提交到oa审批',
      );
    } else {
      this.requestSubmitApprove(params, dispatch);
    }
  }

  removeFile(fileId, file) {
    const { fileList } = this.state;
    const newFileList = _.filter(fileList, data => data.uid !== file.uid);
    const { dispatch } = this.props;
    const params = {
      fileId,
    };
    dispatch({
      type: 'Approve/deleteFile',
      payload: { params },
      callback: data => {
        if (data) {
          this.setState({
            fileList: newFileList,
          });
          message.success(`${data.message}`);
        }
      },
    });
  }

  saveDescription(data) {
    this.setState({
      description: data.target.value,
    });
  }

  render() {
    const {
      basicInfo,
      approvedInfo,
      allgoodsValueDetail,
      expandedRowKeys,
      allgoodsValue,
      bulidWarnInfoList,
      coreWarnInfoList,
      bulletinWarnInfo,
      backTacticsWarnInfoList,
      warnFlag,
      contrastType,
    } = this.props.approve;
    const { action, taskId } = this.props.location.query;
    const { loading, fileLoading, fileList, description } = this.state;
    let hasOaInstanceId = false;
    let isEdit = false;
    // 是否已有oa流程实例
    if (basicInfo && basicInfo.instanceId && basicInfo.instanceId !== '') {
      hasOaInstanceId = true;
    }
    // 是否是修改状态 action=modify
    if (action && action === 'modify') {
      isEdit = true;
    }
    // 是否是oa驳回门户待办 taskId=xxx
    if (taskId && taskId !== '') {
      isEdit = true;
    }

    const showExport = basicInfo.state === 'approval_success'; // 通过审批展示导出按钮
    return (
      <div className={styles.approve} style={{ padding: isEdit ? '0 100px' : '0' }}>
        {/* 审批项目名称 */}
        {isEdit ? (
          <Row justify="center" align="middle">
            <Col md={24}>
              {basicInfo && basicInfo.projectName ? (
                <div className={styles.headerTitle}>
                  {`【货值审批】${basicInfo.projectName}货值审批`}
                </div>
              ) : null}
            </Col>
          </Row>
        ) : null}
        <Card bordered={isEdit}>
          {/* 内容标题 */}
          {isEdit ? (
            <Row style={{ marginBottom: '0' }}>
              <Col span={24}>
                <div className="title">
                  <i></i>
                  <span>审批内容</span>
                </div>
              </Col>
            </Row>
          ) : null}
          {/* 基本信息 */}
          {basicInfo ? (
            <Row gutter={[50, 10]} style={{ marginBottom: '0' }}>
              <Col span={24}>
                <div className="sub-title">
                  <span>基本信息</span>
                </div>
              </Col>
              <Col span={10}>
                <Descriptions size="small" title="" bordered>
                  <Descriptions.Item label="项目">
                    {basicInfo?.projectName}（{basicInfo.projectCode}）
                  </Descriptions.Item>
                </Descriptions>
              </Col>
              <Col span={7}>
                <Descriptions size="small" title="" bordered>
                  <Descriptions.Item label="区域">{basicInfo?.area}</Descriptions.Item>
                </Descriptions>
              </Col>
              <Col span={7}>
                <Descriptions size="small" title="" bordered>
                  <Descriptions.Item label="权益比例">
                    {basicInfo?.quityRatio * 1}%
                  </Descriptions.Item>
                </Descriptions>
              </Col>
            </Row>
          ) : null}
          {/* 本次填报版本  */}
          <Row gutter={[50, 10]} style={{ marginBottom: '0' }}>
            <Col span={24}>
              <div className="sub-title">本次填报版本 </div>
            </Col>
            {approvedInfo
              ? _.map(approvedInfo, (value, key) => (
                  <Col key={key} span={8}>
                    <Descriptions size="small" title="" bordered>
                      <Descriptions.Item label={key}>
                        <a
                          onClick={() => {
                            window.open(`${window.location.origin}/#/ValueManage/PriceManage`);
                          }}
                        >
                          {value}
                        </a>
                      </Descriptions.Item>
                    </Descriptions>
                  </Col>
                ))
              : null}
          </Row>

          {/* 全盘货值差异 */}
          <Row gutter={50} type="flex">
            {allgoodsValue && allgoodsValue.length > 0 ? (
              <Col span={24}>
                <div className="sub-title">
                  <span>全盘货值差异</span>
                  {showExport && basicInfo?.differenceExportStatus ? (
                    <Dropdown
                      trigger={['click']}
                      overlay={
                        <Menu onClick={({ key }) => this.onClickExportExcel(key)}>
                          <Menu.Item key="EXPORT_1">
                            <a>导出全盘差异概览</a>
                          </Menu.Item>
                          <Menu.Item key="EXPORT_2">
                            <a>导出全盘差异详情</a>
                          </Menu.Item>
                        </Menu>
                      }
                    >
                      <a>
                        导出 <Icon type="down" />
                      </a>
                    </Dropdown>
                  ) : null}
                </div>

                <Tabs
                  // tabBarExtraContent={operations}
                  animated={false}
                  onChange={key => this.handleTabsKeyChange(key)}
                >
                  {allgoodsValue.map(item => (
                    <TabPane
                      tab={`VS ${item.versionName}`}
                      key={item.type}
                      style={{ padding: '1px' }}
                    >
                      <Row gutter={[0, 10]}>
                        <Col span={24}>
                          <Row type="flex" justify="space-between" align="middle">
                            <Col>{`与${item.versionName}全盘差异概览`}</Col>
                          </Row>
                          <DifferenceOlive allgoodsValue={allgoodsValue} tabkey={item.type} />
                        </Col>
                        <Col span={24}>
                          <Row type="flex" justify="space-between" align="middle">
                            <Col>{`与${item.versionName}全盘差异详情`}</Col>
                            {/*  */}
                          </Row>
                          {allgoodsValueDetail && allgoodsValueDetail.length > 0 ? (
                            <DifferenceDetail
                              allgoodsValueDetail={allgoodsValueDetail}
                              expandedRowKeys={expandedRowKeys}
                              name={item.versionName}
                            />
                          ) : (
                            <div className="xh-difference-detail-content">
                              <PageEmpty emptyTitle="" />
                            </div>
                          )}
                        </Col>
                      </Row>
                    </TabPane>
                  ))}
                </Tabs>
              </Col>
            ) : null}
          </Row>

          {/* 对标预警--- begin */}
          <>
            {/* 本次调价楼栋 */}
            <PriceAdjustmentBuilding
              data={bulidWarnInfoList}
              showExport={showExport && basicInfo?.warnInfoExportStatus}
              onClickExportExcel={() => this.onClickExportExcel('EXPORT_3')}
            />
            {/* 本次调价对整盘核心指标的影响 */}
            <IndicatorImpact
              data={coreWarnInfoList}
              handleChange={this.handleChangeIndicators}
              isEdit={isEdit}
              showExport={showExport && basicInfo?.warnInfoExportStatus}
              onClickExportExcel={() => this.onClickExportExcel('EXPORT_4')}
            />
            {/* 本次调整预警简报 */}
            <WarningBriefing
              data={bulletinWarnInfo}
              contrastType={contrastType}
              warnFlag={warnFlag}
            />
            {/* 项目背景与价格策略 */}
            <ProjectBackgroundStrategy
              data={backTacticsWarnInfoList}
              handleChange={this.handleChangeProjectBackgroundStrategy}
              isEdit={isEdit}
              warnFlag={warnFlag}
            />
          </>
          {/* 对标预警 --- end */}

          {/* 审批要点说明 */}
          {isEdit ? (
            <Row>
              <Col span={24}>
                <div className="sub-title">审批要点说明</div>
                <TextArea
                  autoSize
                  rows={1}
                  maxLength={500}
                  value={description}
                  onChange={desc => this.saveDescription(desc)}
                ></TextArea>
              </Col>
            </Row>
          ) : (
            <Row>
              <Col span={24}>
                <div className="sub-title">审批要点说明</div>
                <TextArea
                  style={{ resize: 'none' }}
                  value={basicInfo.description}
                  disabled
                  autosize
                />
              </Col>
            </Row>
          )}
          {/* 附件 */}
          {isEdit ? (
            <Row>
              <Col span={24}>
                <div className="sub-title">附件 </div>
                <Spin spinning={fileLoading} tip="上传中...">
                  <Dragger
                    action={file => {
                      const self = this;
                      const fromData = new FormData();
                      fromData.append('file', file);
                      if (file.size > 20480000) {
                        message.warning('单个文件最大上传20M.');
                        return;
                      }
                      self.setState({
                        fileLoading: true,
                      });
                      createUploadUsingPOST({ data: fromData }).then(data => {
                        if (data.code === 1) {
                          const newfileList = [
                            ...fileList,
                            {
                              uid: data.data.fileId,
                              name: data.data.fileName,
                              filePath: data.data.filePath,
                              previewUrl: data.data.previewUrl,
                              status: 'done',
                            },
                          ];
                          self.setState({
                            fileList: newfileList,
                            fileLoading: false,
                          });
                          if (!data.data.message) {
                            message.success(`${file.name} 上传成功.`);
                          } else {
                            message.error(`${data.data.message} 请删除`);
                          }
                        }
                      });
                    }}
                    name="file"
                    multiple={false}
                    fileList={fileList}
                    onRemove={file => {
                      this.removeFile(file.uid, file);
                    }}
                    onDownload={file => this.download(file)}
                  >
                    <p className="ant-upload-drag-icon">
                      <Icon type="inbox" />
                    </p>
                    <p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
                    <p className="ant-upload-hint">单个文件最大上传20M.</p>
                  </Dragger>
                </Spin>
              </Col>
            </Row>
          ) : (
            <>
              {basicInfo.files && basicInfo.files.length ? (
                <Row>
                  <Col span={24}>
                    <div className="sub-title">附件 </div>
                    {_.map(basicInfo.files, (element, key) => (
                      <>
                        <FileBtn
                          fileId={element.fileId}
                          fileName={element.fileName}
                          clickType="textClick"
                          titleNmae
                          key={key}
                          download
                        />
                      </>
                    ))}
                  </Col>
                </Row>
              ) : null}
            </>
          )}
          {/* 按钮 */}
          {isEdit ? (
            <Row type="flex" justify="center" gutter={[10]}>
              {/* 提交到OA审批 */}
              <Col>
                <Button type="primary" loading={loading} onClick={() => this.handApprove()}>
                  提交到OA审批
                </Button>
              </Col>
              {/* 返回修改 */}
              <Col>
                <Button
                  onClick={() => {
                    window.location.href = `${window.location.origin}/#/ValueManage/PriceManage`;
                  }}
                >
                  返回修改
                </Button>
              </Col>
              {/* 查看审批 (有流程实例) */}
              {hasOaInstanceId ? (
                <Col>
                  <Button
                    type="primary"
                    onClick={() => {
                      window.location.href = basicInfo.reviewUrl;
                    }}
                  >
                    查看审批
                  </Button>
                </Col>
              ) : null}
              {/* 废弃 (有流程实例) */}
              {hasOaInstanceId &&
              basicInfo.state &&
              (basicInfo.state === 'reject' || basicInfo.state === 'recall') ? (
                <Col>
                  <Button
                    onClick={() => {
                      showConfirm(
                        () => {
                          api
                            .endFlowUsingPUT({
                              params: {
                                instanceId: basicInfo.instanceId,
                              },
                            })
                            .then(result => {
                              message.loading('废弃流程中...', () => {
                                if (result.code === 1) {
                                  message.success(result.message, () => {
                                    window.location.href = `${window.location.origin}/#/ValueManage/PriceManage`;
                                  });
                                }
                              });
                            });
                        },
                        '是否要废弃该流程?',
                        '确定后将作废该流程后返回货值填报',
                      );
                    }}
                  >
                    废弃
                  </Button>
                </Col>
              ) : null}
              {/* 关闭 */}
              <Col>
                <Button
                  className="red-button"
                  type="primary"
                  onClick={() => {
                    if (navigator.userAgent.indexOf('MSIE') > 0) {
                      // close IE
                      if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
                        window.opener = null;
                        window.close();
                      } else {
                        window.open('', '_top');
                        window.top.close();
                      }
                    } else {
                      // close chrome;It is effective when it is only one.
                      window.opener = null;
                      window.open('', '_self');
                      window.close();
                    }
                  }}
                >
                  关闭
                </Button>
              </Col>
            </Row>
          ) : null}
        </Card>
      </div>
    );
  }
}
export default Approve;
